import network
import socket
import time
import re

# 最大尝试重连
MAX_TRIES = 3


def auto_connect_wifi(filename="wifi_credentials.txt"):
    ssid, password = load_wifi_credentials(filename)
    if ssid and password:
        wlan = network.WLAN(network.STA_IF)
        wlan.active(True)
        if wlan.isconnected():
            return True

        wlan.connect(ssid, password)
        for _ in range(MAX_TRIES):
            if wlan.isconnected():
                return True
            print("Waiting for connection...")
            time.sleep(3)
        # 你的配网代码逻辑
        print("自动连接wifi失败，请重新配网。")
        config_wifi()
    else:
        print("没有找到本地wifi配置文件，请重新配网。")
        # 你的配网代码逻辑
        config_wifi()


# 连接wifi方法
def config_wifi():
    # 初始化 Wi-Fi 接入点
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid="ESP32-Config")
    # 设置 Web 服务器监听连接
    addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
    s = socket.socket()
    # 确保 socket 被关闭，这通常只有在你需要重新启动脚本时才有必要
    s.close()
    # 重新创建一个新的 socket 对象进行监听
    s = socket.socket()
    s.bind(addr)
    s.listen(1)
    print("listening on", addr)
    # 网页内容，用于用户输入 Wi-Fi 设置
    login_page = load_html("pages/connectwifi.html")
    wifiStatus = False
    while not wifiStatus:
        conn, addr = s.accept()
        print("连接来自:", addr)
        request = conn.recv(1024).decode("utf-8")
        # print('请求内容:', request)

        # 解析请求头和数据
        headers = request[: request.find("\r\n\r\n") + 4]
        method, path, protocol = headers.split("\r\n")[0].split(" ")
        content_length = 0
        post_data = ""

        # 判断是否是POST请求
        ssid, password = None, None
        if method == "POST" and "Content-Length:" in headers:
            lines = headers.split("\r\n")
            for line in lines:
                if line.startswith("Content-Length:"):
                    content_length = int(line.split(": ")[1])
                    break

            post_data = request[-content_length:]
            ssid_search = re.search(r"ssid=([^&]+)", post_data)
            password_search = re.search(r"password=([^&]+)", post_data)
            if ssid_search:
                ssid = ssid_search.group(1)
            if password_search:
                password = password_search.group(1)

        # 如果收到SSID和密码，尝试连接Wi-Fi
        if ssid and password:
            ssid = url_decode(ssid)
            password = url_decode(password)
            wlan = connect_wifi(ssid, password)
            # 根据连接结果显示不同的信息
            if wlan.isconnected():
                wifiStatus = True
                save_wifi_credentials(ssid, password)
                response = """
                <html>
                    <body>
                        <h1>连接成功!</h1>
                        <p>IP: {}</p>
                    </body>
                    </html>
                """.format(
                    wlan.ifconfig()[0]
                )
            else:
                response = """
                <html>
                    <body>
                        <h1>连接失败，请检查SSID和密码是否正确。</h1>
                    </body>
                </html>
                """
        else:
            response = login_page

        # 发送HTTP响应
        conn.send("HTTP/1.0 200 OK\r\nContent-type: text/html; charset=UTF-8\r\n\r\n")
        conn.sendall(response)
        conn.close()


# 加载html方法
def load_html(filename):
    try:
        with open(filename, "r") as file:
            return file.read()
    except OSError as e:
        print("无法打开文件：", e)
        return ""


# 连接到指定的Wi-Fi网络
def connect_wifi(ssid, password):
    print("开始连接。。。")
    wlan = network.WLAN(network.STA_IF)
    if wlan.active() and wlan.isconnected():
        print("Wi-Fi已连接")
        return wlan
    wlan.active(True)
    wlan.disconnect()
    wlan.connect(ssid, password)
    start_time = time.time()
    while not wlan.isconnected():
        if time.time() - start_time > 10:
            print("连接超时,尝试重新连接。。。")
            return
        time.sleep(1)
    print("连接成功")
    print(wlan.ifconfig())
    return wlan


# 用于URL解码的函数
def url_decode(s):
    # URL解码的基本实现，你可能需要根据需要添加更多的字符映射
    hex_chars = "0123456789ABCDEFabcdef"
    chars = s.split("%")
    for i in range(1, len(chars)):
        p = chars[i]
        if len(p) >= 2 and p[0] in hex_chars and p[1] in hex_chars:
            chars[i] = bytes([int(p[:2], 16)]).decode("utf-8") + p[2:]
    return "".join(chars).replace("+", " ")


# 保存wifi配置
def save_wifi_credentials(ssid, password, filename="wifi_credentials.txt"):
    with open(filename, "w") as file:
        file.write(ssid + "\n")
        file.write(password + "\n")


# 加载wifi配置
def load_wifi_credentials(filename="wifi_credentials.txt"):
    try:
        with open(filename, "r") as file:
            ssid = file.readline().strip()
            password = file.readline().strip()
            return ssid, password
    except OSError:
        return None, None  # 如果文件不存在，返回None
